package com.boarsoft.boar.gateway;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.cache.aop.Cached;

@Component
@RestController
public class Controller {
	private static final Logger log = LoggerFactory.getLogger(Controller.class);

	@Autowired(required = false)
	protected LoadBalancerClient balancer;
	// @Autowired
	// protected DiscoveryClient discoveryClient;
	// @Autowired
	// protected ServiceRegistry serviceRegistry;
	// @Autowired
	// private Environment environment;

	@RequestMapping("/{app}/**")
	public void route(@PathVariable(required = true) String app, //
			@RequestHeader HttpHeaders headers, //
			HttpServletRequest request, HttpServletResponse response)//
			throws ServletException, IOException {
		// 取出四要素，查询POD
		// headers.get("a");
		// headers.get("b");
		// headers.get("c");
		// headers.get("d");
		int pod = this.route("test");
		log.debug("Find an instance of {} application in POD {}", app, pod);
		StringBuilder sb = new StringBuilder();
		String appId = sb.append("pod").append(pod).append("-").append(app).toString();
		// 调用负载均衡
		ServiceInstance si = balancer.choose(appId);
		// 或自己控制负载均衡
		// List<ServiceInstance> siLt = discoveryClient.getInstances(service);
		// 没找到则重定向到404
		if (si == null) {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		sb.setLength(0);
		String path = request.getRequestURI().substring(app.length() + 1);
		String uri = sb.append(si.getUri()).append(path).toString();
		log.info("Forward to service instance {}", uri);
		//request.getRequestDispatcher(uri).forward(request, response);
	}

	@Cached(group = "routing")
	public int route(String key) {
		return 0; // TODO
	}
}
